<!--user管理页-->
<template>
  <div style="height:6vh;padding:10px 20px;background-color:#fff;">
    <span style="line-height:60px;font-size:20px;">学员管理</span>
    <el-button type="primary" @click="beforeAddUser" style="float: right;margin-top:10px;">新建学员
    </el-button>
  </div>
  <!-- 新建用户弹窗 -->
  <el-dialog :title="dialogTitle" style="width: 1000px;padding:40px;" v-model="dialogVisible"
    :before-close="handleClose">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="姓名">
            <el-input placeholder="请输入学员姓名" v-model="saveUserForm.username"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="所属部门">
            <el-select placeholder="请选择" v-model="saveUserForm.departmentName" @change="loadDepartmentName">
              <el-option v-for="item in departmentNameOptions" :label="item.value" :value="item.value" ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveUser">保存</el-button>
    </template>
  </el-dialog>

  <!-- 加减分操作弹窗 -->
  <el-dialog title="积分操作" style="width: 500px;padding:20px;" v-model="scoreDialogVisible">
    <el-form label-width="80px" label-position="top" ref="scoreFormRef">
      <el-form-item label="操作类型">
        <el-select placeholder="请选择" v-model="scoreForm.actionType">
          <el-option label="加分" value="add"></el-option>
          <el-option label="减分" value="subtract"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="分数" :error="scoreError">
        <el-input placeholder="请输入分数" v-model="scoreForm.score" @input="validateScore"></el-input>
      </el-form-item>

      <el-form-item label="原因">
        <el-input type="textarea" placeholder="请输入加减分原因" v-model="scoreForm.reason" :rows="3"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="scoreDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitScore">提交</el-button>
    </template>
  </el-dialog>

  <!-- 用户搜索卡片 -->
  <el-card style="margin: 20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="用户搜索">
        <el-input placeholder="请输入名字" style="width: 220px;" v-model="searchUserForm.username"
          @keydown.enter="loadUser"></el-input>
      </el-form-item>
      <el-form-item label="所属部门" style="width: 290px;">
        <el-select placeholder="请选择部门" v-model="searchUserForm.departmentName" @change="loadUser" >
          <el-option v-for="item in departmentNameOptions"
                     :label="item.label" :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadUser">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 用户数据表格卡片 -->
  <el-card style="margin: 20px;">
    <el-table :data="userArr">
      <el-table-column type="index" label="编号" width="80" align="center"></el-table-column>
      <el-table-column label="姓名" prop="username" align="center"></el-table-column>
      <el-table-column label="所属部门" prop="departmentName" align="center"></el-table-column>
      <el-table-column label="总分" prop="total" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="success" @click="openScoreDialog(scope.row.id, 'add')">加分</el-button>
          <el-button link type="warning" @click="openScoreDialog(scope.row.id, 'subtract')">减分</el-button>
          <el-button link type="primary" @click="editUser(scope.row.id)">编辑</el-button>
          <el-button link type="primary" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script setup>
import { onMounted, ref } from "vue";
import axios, {options} from "axios";
import qs from "qs";
import { ElMessage } from "element-plus";

// 定义变量控制弹窗是否出现
const dialogVisible = ref(false);
const scoreDialogVisible = ref(false);
// 定义变量用来控制弹窗的标题
const dialogTitle = ref('新建用户');

// 定义对象用来保存表单中的学生数据
const saveUserForm = ref({
  id: '',
  username: '',
  departmentName: '',
  total: ''
});

// 定义对象用来保存积分操作的数据
const scoreForm = ref({
  userId: '',
  actionType: 'add',
  score: '',
  reason: ''
});
const scoreFormRef = ref(null); // 用于表单验证的引用
const scoreError = ref(''); // 用于显示分数输入的错误信息

// 定义数组来维护部门的选项
const departmentNameOptions = ref([
  { label: '云启一部', value: '云启一部' },
  { label: '2', value: '20' },
  { label: '3', value: '30' },
  { label: '4', value: '40' },
  { label: '5', value: '40' },
  { label: '6', value: '40' }
]);

/* 点击"新建学员"按钮，出弹窗+修改弹窗标题 */
const beforeAddUser = () => {
  dialogVisible.value = true;
  dialogTitle.value = '新增学员';
}

/* 点击弹窗中的“保存用户”按钮 => 新增+更新用户 */
const saveUser = () => {
  console.log(saveUserForm.value);
  let data = qs.stringify(saveUserForm.value);
  console.log(data);
  axios.post(BASE_URL + '/v1/user/save', data)
    .then((response) => {
      if (response.data.code == 2000) {
        ElMessage.success('保存成功!');
        // 用户确认关闭后,关闭弹窗
        dialogVisible.value = false;
        // 清空已输入的表单数据
        saveUserForm.value = {};
        // 重新加载用户数据
        loadUser();
      } else {
        ElMessage.error(response.data.msg);
      }
    })
}

const loadDepartmentName = () => {
  axios.get(BASE_URL + '/v1/departmentinfo/selectDepartmentName')
      .then((response) => {
        if (response.data.code === 2000) {
          // 将字符串数组转换为 { label: name, value: name } 结构
          departmentNameOptions.value = response.data.data.map(name => ({
            label: name,
            value: name
          }));
          console.log(departmentNameOptions)
        } else {
          ElMessage.error(response.data.msg);
        }
      })
}


// 处理弹窗关闭的方法
const handleClose = () => {
  if (confirm('确认要关闭本窗口吗?')) {
    // 用户确认关闭后,关闭弹窗
    dialogVisible.value = false;
    // 清空已输入的表单数据
    saveUserForm.value = {};
  }
}

// 定义对象来保存用户查询的条件
const searchUserForm = ref({ username: '', departmentName: '' });
// 定义对象保存查询到的用户表格数据
const userArr = ref([]);
// 定义加载用户列表的方法
const loadUser = () => {
  let data = qs.stringify(searchUserForm.value);
  // 如果有查询条件,就根据条件查,没有条件默认查全部数据
  axios.get(BASE_URL + '/v1/user/select?' + data)
    .then((response) => { //回调函数,处理响应数据
      if (response.data.code == 2000) { //后端返回的状态码是2000说明成功了
        console.log(response.data.data);
        userArr.value = response.data.data; //把请求回来的数据装到绑定表格的数组中
        console.log(userArr.value);
      } else {
        ElMessage.error(response.data.msg);
      }
    })
}

// 页面一加载完毕,立即执行
onMounted(() => {
  loadUser();
  loadDepartmentName();
})

// 重置搜索
const resetSearch = () => {
  // 清空之前的搜索内容
  searchUserForm.value = {};
  // 重新加载所有的用户数据
  loadUser();
}

/* 点击用户表格的"编辑"按钮，出弹窗+修改弹窗标题 */
// 定义编辑学员的方法
const editUser = (id) => {
  // 让弹窗出现
  dialogVisible.value = true;
  // 修改弹窗的标题
  dialogTitle.value = '编辑学员';
  // 根据id查询用户信息并回显在弹窗的表单中
  console.log(id)
  axios.get(BASE_URL + '/v1/user/select?id=' + id).then((response) => {
    if (response.data.code == 2000) {
      // 注意:后端返回的是List<UserVO>,所以查一条数据的话拿的是集合的第一个元素data[0]
      saveUserForm.value = response.data.data[0];
    } else {
      ElMessage.error(response.data.msg);
    }
  })
}

// 创建删除员工的方法
const deleteUser = (userId) => {
  if (confirm('您确认要删除该员工吗?')) {
    axios.post(BASE_URL + '/v1/user/delete/' + userId).then((response) => {
      if (response.data.code == 2000) {
        ElMessage.success('删除成功!');
        // 删除成功后,需要重新加载用户列表
        loadUser();
      } else {
        ElMessage.error(response.data.msg);
      }
    })
  }
}

// 打开积分操作弹窗
const openScoreDialog = (userId, actionType) => {
  scoreForm.value.userId = userId;
  scoreForm.value.actionType = actionType;
  scoreDialogVisible.value = true;
}

// 验证分数输入
const validateScore = () => {
  scoreError.value = '';
  const score = scoreForm.value.score;
  if (!score) {
    scoreError.value = '请输入分数';
    return false;
  }
  if (!/^[0-9]+$/.test(score)) {
    scoreError.value = '请输入有效数字';
    return false;
  }
  return true;
}

// 提交积分操作
const submitScore = async () => {
  // 验证输入的分数是否为有效数字
  if (!validateScore()) return;

  const { userId, actionType, score, reason } = scoreForm.value;

  // 查询用户当前学分
  const user = await getUserScore(userId);
  if (!user) return;

  if (actionType === 'subtract' && user.total < parseInt(score)) {
    ElMessage.error('学分不足，无法减分');
    return;
  }

  axios.post(BASE_URL + `/v1/user/${actionType}Score/${userId}?points=${score}&reason=${reason}`)
    .then((response) => {
      if (response.data.code == 2000) {
        ElMessage.success(`${actionType === 'add' ? '加分' : '减分'}成功!`);
        // 操作成功后,关闭弹窗并刷新用户列表
        scoreDialogVisible.value = false;
        loadUser();
      } else {
        ElMessage.error(response.data.msg);
      }
    })
}

// 获取用户当前学分
const getUserScore = (userId) => {
  return new Promise((resolve) => {
    axios.get(BASE_URL + '/v1/user/select?id=' + userId).then((response) => {
      if (response.data.code == 2000 && response.data.data.length > 0) {
        resolve(response.data.data[0]);
      } else {
        ElMessage.error('获取用户信息失败');
        resolve(null);
      }
    });
  });
}
</script>


<style scoped>
/* 全局视觉体系 */
:global(body) {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: blue;
  font-size: 16px;
}

:root {
  --primary-gradient: linear-gradient(45deg, #ff6f00 0%, #ffca28 100%);
  --dark-bg: #1a1a1a;
  --table-bg: #2d2d2d;
  --hover-bg: #3d3d3d;
  --border-color: #4a4a4a;
  --text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  --spacing-base: 1.2rem;
  --spacing-card: 1.2rem;
  --spacing-table: 1.5rem;
}

/* 用户管理页深色主题 */
.head {
  background: var(--primary-gradient);
  color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

.headTitle {
  font-size: 22px;
  color: white;
  font-weight: 600;
  text-shadow: var(--text-shadow);
}

/* 卡片容器 */
.el-card {
  margin: var(--spacing-card);
  border-radius: 14px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
  background-color: var(--dark-bg);
  color: #fff;
}

/* 表格样式 */
.el-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  background-color: var(--table-bg);
  color: #000000;
}

.el-table__row {
  transition: background-color 0.3s ease;
  background-color: var(--table-bg);
  color: #000000;
  font-size: 15px;
}

.el-table__row:hover {
  background-color: var(--hover-bg) !important;
}

/* 弹窗样式 */
.el-dialog {
  border-radius: 16px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
  background-color: var(--dark-bg);
  color: #fff;
}

/* 表单样式 */
.el-form-item {
  margin-bottom: var(--spacing-base);
}

.el-form-item label {
  color: #fff;
  font-weight: 600;
  font-size: 15px;
}

.el-input__inner {
  border-radius: 8px;
  border: 1px solid #ffca28;
  transition: all 0.3s ease;
  background-color: #3d3d3d;
  color: #fff;
  font-size: 15px;
  font-weight: 500;
}


.el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 202, 40, 0.5);
}

/* 移动端适配 */
@media (max-width: 768px) {
  :global(body) {
    font-size: 15px;
  }
  
  .el-input__inner {
    font-size: 15px;
  }
  
  .el-table__cell {
    font-size: 14px;
  }
}
</style>